package vboot.core.module.sys.org.tier;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vboot.core.common.api.PageData;
import vboot.core.common.dao.JdbcDao;
import vboot.core.common.dao.Sqler;
import vboot.core.common.pojo.ZidName;
import vboot.core.xutil.lang.XstrUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class SysOrgTierNodeService {

    @Transactional(readOnly = true)
    public SysOrgTierNode findById(String id) {
        return nodeRepo.findById(id).get();
    }

    public SysOrgTierNode insert(SysOrgTierNode main) {
        if (main.getId() == null || "".equals(main.getId())) {
            main.setId(XstrUtil.getUUID());
        }
        if (main.getParent() == null || StrUtil.isBlank(main.getParent().getId())) {
            main.setTier("x" + main.getId() + "x");
        } else {
            String tier = jdbcDao.findOneString("select tier from sys_org_tier_node where id=?", main.getParent().getId());
            main.setTier(tier + main.getId() + "x");
        }
        return nodeRepo.save(main);
    }


    public SysOrgTierNode update(SysOrgTierNode main) throws Exception {
        main.setUptim(new Date());
        if (main.getParent() == null || StrUtil.isBlank(main.getParent().getId())) {
            main.setTier("x" + main.getId() + "x");
        } else {
            String tier = jdbcDao.findOneString("select tier from sys_org_tier_node where id=?", main.getParent().getId());
            main.setTier(tier + main.getId() + "x");
            String[] arr = tier.split("x");
            for (String str : arr) {
                if (main.getId().equals(str)) {
                    throw new Exception("父层级不能为自己或者自己的子层级");
                }
            }
        }
        SysOrgTierNode backTier = nodeRepo.save(main);
        String oldTier = jdbcDao.findOneString("select tier from sys_org_tier_node where id=?", main.getId());
        dealTier(oldTier, main.getTier(), main.getId());
        return backTier;
    }

    public int delete(String[] ids) {
        for (String str : ids) {
            nodeRepo.deleteById(str);
        }
        return ids.length;
    }

    private void dealTier(String oldTier, String newTier, String id) {
        String sql = "select id,tier as name from sys_org_tier_node where tier like ? and id<>?";
        List<ZidName> list = jdbcDao.findIdNameList(sql, oldTier + "%", id);
        String updateSql = "update sys_org_tier_node set tier=? where id=?";
        List<Object[]> updateList = new ArrayList<Object[]>();
        batchReady(oldTier, newTier, list, updateList);
        jdbcDao.batch(updateSql, updateList);
    }


    private void batchReady(String oldTier, String newTier, List<ZidName> list, List<Object[]> updateList) {
        for (ZidName ztwo : list) {
            Object[] arr = new Object[2];
            arr[1] = ztwo.getId();
            arr[0] = ztwo.getName().replace(oldTier, newTier);
            updateList.add(arr);
        }
    }

    public List<SysOrgTierNode> findAll(Sqler sqler) {
        List<SysOrgTierNode> list = jdbcDao.getTp().query(sqler.getSql(), sqler.getParams(), new BeanPropertyRowMapper<>(SysOrgTierNode.class));
        return list;
    }

    public PageData findPageData(Sqler sqler) {
        return jdbcDao.findPageData(sqler);
    }

    public List<SysOrgTierNode> findTree(Sqler sqler) {
        List<SysOrgTierNode> list = jdbcDao.getTp().query(sqler.getSql(), sqler.getParams(), new BeanPropertyRowMapper<>(SysOrgTierNode.class));
        return buildByRecursive(list);
    }

    //使用递归方法建树
    private List<SysOrgTierNode> buildByRecursive(List<SysOrgTierNode> nodes) {
        List<SysOrgTierNode> list = new ArrayList<>();
        for (SysOrgTierNode node : nodes) {
            if (node.getPid() == null) {
                list.add(findChildrenByTier(node, nodes));
            } else {
                boolean flag = false;
                for (SysOrgTierNode node2 : nodes) {
                    if (node.getPid().equals(node2.getId())) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    list.add(findChildrenByTier(node, nodes));
                }
            }
        }
        return list;
    }

    //递归查找子节点
    private SysOrgTierNode findChildrenByTier(SysOrgTierNode node, List<SysOrgTierNode> nodes) {
        for (SysOrgTierNode item : nodes) {
            if (node.getId().equals(item.getPid())) {
                if (node.getChildren() == null) {
                    node.setChildren(new ArrayList<>());
                }
                node.getChildren().add(findChildrenByTier(item, nodes));
            }
        }
        return node;
    }


//    public List<SysOrgTierTree> findWithoutItself(Sqler sqler, String id) {
//        List<SysOrgTierTree> list = jdbcDao.getTp().query(sqler.getSql(), sqler.getParams(), new BeanPropertyRowMapper<>(SysOrgTierTree.class));
//        return buildByRecursiveWithoutItself(list, id);
//    }

    //使用递归方法建树不包含自己
//    private List<SysOrgTierTree> buildByRecursiveWithoutItself(List<SysOrgTierTree> nodes, String id) {
//        List<SysOrgTierTree> list = new ArrayList<>();
//        for (SysOrgTierTree node : nodes) {
//            if (node.getPid() == null && !node.getId().equals(id)) {
//                list.add(findChildrenByTierWithoutItself(node, nodes, id));
//            } else {
//                boolean flag = false;
//                for (SysOrgTierTree node2 : nodes) {
//                    if (node.getPid() != null && node.getPid().equals(node2.getId())) {
//                        flag = true;
//                        break;
//                    }
//                }
//                if (!flag && !node.getId().equals(id)) {
//                    list.add(findChildrenByTierWithoutItself(node, nodes, id));
//                }
//            }
//        }
//        return list;
//    }

    //递归查找子节点不包含自己
//    private SysOrgTierTree findChildrenByTierWithoutItself(SysOrgTierTree node, List<SysOrgTierTree> nodes, String id) {
//        for (SysOrgTierTree item : nodes) {
//            if (node.getId().equals(item.getPid()) && (!item.getId().equals(id))) {
//                if (node.getChildren() == null) {
//                    node.setChildren(new ArrayList<>());
//                }
//                node.getChildren().add(findChildrenByTierWithoutItself(item, nodes, id));
//            }
//        }
//        return node;
//    }

    @Autowired
    private JdbcDao jdbcDao;

    @Autowired
    private SysOrgTierNodeRepo nodeRepo;


}
